package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.FileConfigInfo;
import com.sywb.chuangyebao.bean.QARichInfo;
import com.sywb.chuangyebao.bean.UploadInfo;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.AskActivity;
import com.sywb.chuangyebao.view.dialog.AskAudioDialog;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.BaseRecyclerDivider;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemChildClickListener;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.PermissionsPresenter;
import org.bining.footstone.rxjava.luban.Luban;
import org.bining.footstone.rxjava.luban.OnCompressListener;
import org.bining.footstone.utils.FileUtils;
import org.bining.footstone.utils.SharedUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public interface AskContract {

    interface AskView extends IView {

        /**
         * 获取 RecyclerView
         */
        RecyclerView getRecyclerView();

        /**
         * 设置获取数据完毕时的界面展示
         */
        void setNoData(boolean isNoData);

        void picSizeChanged(int size);
    }

    class Presenter extends PermissionsPresenter<AskView> {

        protected RecyclerView commonRecycler;

        protected BaseRecyclerDivider recyclerDivider;

        private PicAdapter adapter;

        @Override
        public void onStart() {
            commonRecycler = mView.getRecyclerView();

            if (commonRecycler != null && useRecyclerDivider()) {
                recyclerDivider = new BaseRecyclerDivider();
                commonRecycler.addItemDecoration(recyclerDivider);
            }
            adapter = new PicAdapter(mActivity);
            commonRecycler.setAdapter(adapter);
            commonRecycler.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
        }

        public boolean useRecyclerDivider() {
            return true;
        }

        public void addPic(List<String> imagePaths) {
            adapter.addDatas(imagePaths);
            mView.picSizeChanged(adapter.getDataCount());
        }

        @Override
        public void onPermissionsSuccess(String[] strings) {
//            new AskAudioDialog(mActivity).show();

            AskAudioDialog dialogFragment = AskAudioDialog.newInstance();
            dialogFragment.show(mView.getMyFragmentManager(), "Ask");

        }

        @Override
        public void onPermissionsFailure(String strMsg) {
            super.onPermissionsFailure(strMsg);
            showMessage(strMsg);
        }

        public void publish(final int comingType, final long questionId, final String input, String voiceLocalPath, final List<QARichInfo> richInfoList, final long topicId, final int voiceLength) {
            switch (comingType) {
                case AskActivity.COMING_TYPE_ASK:
                    if (TextUtils.isEmpty(input)) {
                        showMessage(R.string.ask_hint);
                        return;
                    }
                    break;
                case AskActivity.COMING_TYPE_ANSWER:
                    if (TextUtils.isEmpty(input)) {
                        showMessage(R.string.answer_hint);
                        return;
                    }
                    break;
            }

            if (!TextUtils.isEmpty(voiceLocalPath) && FileUtils.isFileExists(voiceLocalPath)) {
                //有语音
                try {
                    //进行上传
                    HttpUtils.uploadHttp(new File(voiceLocalPath), new HttpCallback<List<UploadInfo>>() {

                        @Override
                        public void onStart() {
                            super.onStart();
                            onStartAsync();
                        }

                        @Override
                        public void onSuccess(List<UploadInfo> uploadInfos) {
                            //上传语音成功 继续做发布提问的事情
//                            ToastUtils.show(mActivity, "上传语音成功 继续做发布提问的事情");
                            if (uploadInfos != null && uploadInfos.size() > 0) {
                                goPublish(comingType, questionId, input, new ArrayList<String>(), uploadInfos.get(0).filename, richInfoList, topicId, voiceLength);
                            } else {
                                showMessage(R.string.upload_error);
                            }
                        }

                        @Override
                        public void onError(String strMsg) {
                            super.onError(strMsg);
                            showMessage(strMsg);
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            onFinishAsync();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (adapter.getDataCount() > 0) {
                //添加了图片
                //对图片进行压缩
                Luban.with(mActivity).load(adapter.getDatas()).setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        onStartAsync();
                    }

                    @Override
                    public void onSuccess(List<File> list) {
                        //压缩成功，上传图片
                        //对压缩后的图片进行判断是否符合上传标准
                        String fileConfig = SharedUtils.getString(Constants.USERFILECONFIG, "");
                        if (TextUtils.isEmpty(fileConfig)) {
                            onFinishAsync();
                            showMessage(R.string.upload_error);
                            return;
                        }

                        FileConfigInfo fileConfigInfo = JSON.parseObject(fileConfig, FileConfigInfo.class);
                        if (fileConfigInfo == null) {
                            onFinishAsync();
                            showMessage(R.string.upload_error);
                            return;
                        }

                        try {
                            for (int i = 0; i < list.size(); i++) {
                                File file = list.get(i);
                                String fileType = FileUtils.getFileType(file.getAbsolutePath());
                                int fileMaxSize = fileConfigInfo.mime_types.get(fileType).size;

                                if (FileUtils.getFileSize(file) > fileMaxSize) {
                                    onFinishAsync();
                                    showMessage("您选择的第" + i + "张图太大了,请重新选择");
                                    return;
                                }
                            }

                            //进行上传
                            HttpUtils.uploadHttp(list, new HttpCallback<List<UploadInfo>>() {

                                @Override
                                public void onStart() {
                                    super.onStart();
                                    onStartAsync();
                                    PictureFileUtils.deleteCacheDirFile(mActivity);
                                }

                                @Override
                                public void onFinish() {
                                    super.onFinish();
                                    onFinishAsync();
                                }

                                @Override
                                public void onSuccess(List<UploadInfo> uploadInfos) {
                                    //上传图片成功 继续做发布提问的事情
//                                    ToastUtils.show(mActivity, "上传图片成功 继续做发布提问的事情");
                                    List<String> urls = new ArrayList<>();
                                    for (UploadInfo uploadInfo : uploadInfos) {
                                        urls.add(uploadInfo.filename);
                                    }

                                    goPublish(comingType, questionId, input, urls, "", richInfoList, topicId, voiceLength);
                                }

                                @Override
                                public void onError(String strMsg) {
                                    super.onError(strMsg);
                                    showMessage(strMsg);
                                }
                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        onFinishAsync();
                        showMessage("压缩出错了");
                    }
                }).launch();
            } else {
                goPublish(comingType, questionId, input, new ArrayList<String>(), "", richInfoList, topicId, voiceLength);
            }
        }


        private void goPublish(int comingType, final long questionId, String input, List<String> images, String audio, List<QARichInfo> richInfoList, long topicId, int audioLength) {
            switch (comingType) {
                case AskActivity.COMING_TYPE_ASK:
//                    Logger.e("saveQuestion.input:" + input);
//                    Logger.e("saveQuestion.images:" + JSON.toJSONString(images));
//                    Logger.e("saveQuestion.audio:" + audio);
//                    Logger.e("saveQuestion.richInfoList:" + JSON.toJSONString(richInfoList));
//                    Logger.e("saveQuestion.topicId:" + topicId);
//                    Logger.e("saveQuestion.audioLength:" + audioLength);

                    HttpUtils.saveQuestion(input, images, audio, richInfoList, topicId, audioLength, new HttpCallback<Object>() {

                        @Override
                        public void onStart() {
                            super.onStart();
                            onStartAsync();
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            onFinishAsync();
                        }

                        @Override
                        public void onSuccess(Object s) {
                            showMessage(mContext.getString(R.string.ask_success));
//                            RxBus.get().post(Constants.POST_SAVE_QUESTION, Constants.POST_SAVE_QUESTION);
                            mView.exit();
                        }

                        @Override
                        public void onError(String strMsg) {
                            super.onError(strMsg);
                            showMessage(strMsg);
                        }
                    });
                    break;
                case AskActivity.COMING_TYPE_ANSWER:
//                    Logger.e("saveAnswer.questionId:" + questionId);
//                    Logger.e("saveAnswer.input:" + input);
//                    Logger.e("saveAnswer.images:" + JSON.toJSONString(images));
//                    Logger.e("saveAnswer.audio:" + audio);
//                    Logger.e("saveAnswer.richInfoList:" + JSON.toJSONString(richInfoList));
//                    Logger.e("saveAnswer.audioLength:" + audioLength);

                    HttpUtils.saveAnswer(questionId, input, images, audio, richInfoList, audioLength, new HttpCallback<Object>() {

                        @Override
                        public void onStart() {
                            super.onStart();
                            onStartAsync();
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            onFinishAsync();
                        }

                        @Override
                        public void onSuccess(Object s) {
                            showMessage(mContext.getString(R.string.answer_success));
//                            RxBus.get().post(Constants.POST_SAVE_ANSWER, Constants.POST_SAVE_ANSWER);
                            mView.exit();
                        }

                        @Override
                        public void onError(String strMsg) {
                            super.onError(strMsg);
                            showMessage(strMsg);
                        }
                    });
                    break;
            }
        }

        class PicAdapter extends BaseRecyclerAdapter<String> implements OnItemChildClickListener {

            PicAdapter(Activity activity) {
                super(activity, R.layout.item_ask_pic);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int position, String model) {
                ImageView imageView = viewHolderHelper.getView(R.id.iv_pic);
                GlideUtils.getNormalIamgeToUrl(mActivity, model, imageView, R.drawable.head_image);

                viewHolderHelper.setOnItemChildClickListener(this);
                viewHolderHelper.setItemChildClickListener(R.id.iv_pic_cancel);
                viewHolderHelper.setItemChildClickListener(R.id.iv_pic);
            }

            @Override
            public void onItemChildClick(View view, int i) {
                switch (view.getId()) {
                    case R.id.iv_pic_cancel:
                        adapter.removeItem(i);
                        mView.picSizeChanged(adapter.getDataCount());
                        break;
                    case R.id.iv_pic:
                        Utils.goBigPic(mActivity, i, mDatas);
                        break;
                }
            }
        }

    }

}

